<template>
  <el-dialog title="修改密码" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
    <el-form ref="dataForm" :rules="modelRules" :model="model" label-width="130px">
      <el-tooltip v-model="capsTooltip" content="大写锁定已开启" placement="top" manual>
        <el-form-item label="新密码" prop="password">
          <el-input
            :key="isPasswordType"
            v-model="model.password"
            :type="isPasswordType?'password':''"
            placeholder="新密码"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
          >
            <template slot="append">
              <span class="show-pwd" @click="isPasswordType = !isPasswordType">
                <svg-icon :icon-class="isPasswordType ? 'eye' : 'eye-open'"/>
              </span>
            </template>
          </el-input>
        </el-form-item>
      </el-tooltip>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          :key="isPasswordType"
          v-model="model.confirmPassword"
          :type="isPasswordType?'password':''"
          placeholder="确认密码"
          @keyup.native="checkCapslock"
          @blur="capsTooltip = false"
        >
          <template slot="append">
            <span class="show-pwd" @click="isPasswordType = !isPasswordType">
              <svg-icon :icon-class="isPasswordType ? 'eye' : 'eye-open'"/>
            </span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="shouldChangePasswordOnNextLogin">
        <el-checkbox v-model="model.shouldChangePasswordOnNextLogin">下次登录需要修改密码</el-checkbox>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close()">取消</el-button>
      <el-button type="primary" :loading="isSubmitLoading" @click="save()">提交</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { changePassword, getPasswordComplexitySetting } from "@/api/user";

export default {
  data() {
    const validatePassword = (rule, value, callback) => {
      const givenPassword = value;
      if (!givenPassword || givenPassword.length < 0) {
        callback(new Error(`请输入密码`));
      }

      const requiredLength = this.passwordComplexitySetting.requiredLength;
      if (requiredLength && givenPassword && givenPassword.length < requiredLength) {
        callback(new Error(`密码至少需要${requiredLength}个字符`));
      }

      const requireDigit = this.passwordComplexitySetting.requireDigit;
      if (requireDigit && givenPassword && !/[0-9]/.test(givenPassword)) {
        callback(new Error(`密码必须包含数字`));
      }

      const requireUppercase = this.passwordComplexitySetting.requireUppercase;
      if (requireUppercase && givenPassword && !/[A-Z]/.test(givenPassword)) {
        callback(new Error(`密码必须包含大写字母`));
      }

      const requireLowercase = this.passwordComplexitySetting.requireLowercase;
      if (requireLowercase && givenPassword && !/[a-z]/.test(givenPassword)) {
        callback(new Error(`密码必须包含小写字母`));
      }

      const requireNonAlphanumeric = this.passwordComplexitySetting.requireNonAlphanumeric;
      if (requireNonAlphanumeric && givenPassword && /^[0-9a-zA-Z]+$/.test(givenPassword)) {
        callback(new Error(`密码必须包含标点符号`));
      }

      callback();
    };

    const validateConfirmPassword = (rule, value, callback) => {
      const givenPassword = value;

      if (givenPassword !== this.model.password) {
        callback(new Error(`确认密码和密码必须一致`));
      }

      callback();
    };
    return {
      passwordComplexitySetting: {},
      dialogVisible: false,
      isSubmitLoading: false,
      model: {
        id: undefined,
        password: "",
        confirmPassword: "",
        shouldChangePasswordOnNextLogin: false
      },
      modelRules: {
        password: [
          {
            trigger: "blur",
            validator: validatePassword
          }
        ],
        confirmPassword: [
          {
            trigger: "blur",
            validator: validateConfirmPassword
          }
        ],
        shouldChangePasswordOnNextLogin: [{ required: true }]
      },
      isPasswordType: true,
      capsTooltip: false
    };
  },
  methods: {
    show(id) {
      this.resetModal();
      this.model.id = id;
      getPasswordComplexitySetting().then(result => {
        this.passwordComplexitySetting = result;

        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs["dataForm"].clearValidate();
        });
      });
    },
    resetModal() {
      this.model = {
        id: undefined,
        password: "",
        confirmPassword: "",
        shouldChangePasswordOnNextLogin: false
      };
    },
    save() {
      this.isSubmitLoading = true;
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          changePassword(this.model)
            .then(() => {
              this.$message({ message: "修改成功", type: "success" });
              this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
              this.close();
            })
            .catch(() => {
              this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
            });
        } else {
          this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
          this.$message({ message: this.$t("formIsNotValidMessage"), type: "warning" });
        }
      });
    },
    close() {
      this.dialogVisible = false;
      this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
    },
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if ((shiftKey && (key >= "a" && key <= "z")) || (!shiftKey && (key >= "A" && key <= "Z"))) {
          this.capsTooltip = true;
        } else {
          this.capsTooltip = false;
        }
      }
      if (key === "CapsLock" && this.capsTooltip === true) {
        this.capsTooltip = false;
      }
    }
  }
};
</script>
